package com.iye.puretennis.fragment;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipDescription;
import android.content.Context;
import android.view.DragEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.iye.puretennis.R;
import com.iye.puretennis.custom.DragLongClickListener;
import com.iye.puretennis.custom.HorizontalListView;
import com.iye.puretennis.custom.HuaWenHuPoTextView;
import com.iye.puretennis.custom.draggablegridview.BaseDynamicGridAdapter;
import com.iye.puretennis.domain.*;
import com.iye.puretennis.helper.Constant;
import com.iye.puretennis.helper.RemoteUrlCollections;
import com.iye.puretennis.helper.ServerAccessHelper;
import com.iye.puretennis.helper.Session;
import com.iye.puretennis.utils.JsonUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.LinkedList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: jing wu
 * Date: 2014/12/15
 * Time: 17:51
 */
public class JoinAppointmentFragment extends TabFragment {

    private String appointmentGuid;

    protected Appointment appointment = new Appointment();

    private LinkedList<ListItem> participants = new LinkedList<ListItem>();

    private LinkedList<ListItem> invitations = new LinkedList<ListItem>();

    private LinkedList<ListItem> requests = new LinkedList<ListItem>();

    private HuaWenHuPoTextView invitationText;

    private AppointmentAdapter participantsAdapter;

    private AppointmentAdapter invitationsAdapter;

    private AppointmentAdapter requestsAdapter;

    private HorizontalListView invitationsView;

    private HorizontalListView participantsView;

    private HorizontalListView requestsView;

    private int listViewWidth;

    private int listViewHeight;

    private DragEventListener mDragListener;

    private DragLongClickListener dragLongClickListener;

    private ImageButton joinButton;


    public static final int dividerWidth = 5;

    public static final String TAG = "join_appointment";


    @Override
    public void onCustomCreateView(LayoutInflater inflater) {

        fragmentActivity.hideTabBar();

        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fragmentActivity.showTabBar();
                onBackPressed();
            }
        });

        Session session = Session.newSession();

        appointmentGuid = (String) session.get("appointmentGuid");

        listViewWidth = (width - dividerWidth * 3 - 15) / 5 + 10;

        listViewHeight = listViewWidth + 40;
//
//        invitations.add(new ListItem("1", "1", "so"));
//        invitations.add(new ListItem("2", "2", "like"));
//        invitations.add(new ListItem("3", "3", "do"));
//        invitations.add(new ListItem("3", "3", "add"));
//        invitations.add(new ListItem("3", "3", "cool"));

        invitationsAdapter = new AppointmentAdapter(fragmentActivity, invitations, 5, 1);


//        participants.add(new ListItem("4", "4", "what"));
//        participants.add(new ListItem("5", "5", "that"));
//        participants.add(new ListItem("6", "6", "need"));
//        participants.add(new ListItem("7", "7", "main"));

        participantsAdapter = new AppointmentAdapter(fragmentActivity, participants, 5, 2);

//
//        requests.add(new ListItem("8", "8", "appointment"));
//        requests.add(new ListItem("9", "9", "dota"));
//        requests.add(new ListItem("10", "10", "ten"));
//        requests.add(new ListItem("11", "11", "kunka"));
//        requests.add(new ListItem("12", "12", "sven"));
//        requests.add(new ListItem("13", "13", "lili"));

        requestsAdapter = new AppointmentAdapter(fragmentActivity, requests, 5, 3);


        joinButton = (ImageButton) mainView.findViewById(R.id.join_button);

        invitationText = (HuaWenHuPoTextView) mainView.findViewById(R.id.invitation_text);

        invitationsView = (HorizontalListView) mainView.findViewById(R.id.invitations_view);

        invitationsView.getLayoutParams().height = listViewHeight;

        invitationsView.setAdapter(invitationsAdapter);

        participantsView = (HorizontalListView) mainView.findViewById(R.id.participants_view);

        participantsView.getLayoutParams().height = listViewHeight;

        participantsView.setAdapter(participantsAdapter);

        requestsView = (HorizontalListView) mainView.findViewById(R.id.requests_view);

        requestsView.getLayoutParams().height = listViewHeight;

        requestsView.setAdapter(requestsAdapter);

    }

    @SuppressLint("NewApi")
    protected class DragEventListener implements View.OnDragListener {


        // 该方法由系统调用，当有拖拽事件发生时
        @SuppressLint("ShowToast")
        public boolean onDrag(View v, DragEvent event) {
            // 定义一个变量来存储通过事件传递的action类型
            final int action = event.getAction();
            // 每个事件的处理
            switch (action) {

                case DragEvent.ACTION_DRAG_STARTED:
                    // 确定是否这个视图（View）可以接收拖拽的数据类型
                    if (event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {

                        // 通过返回true来表明View可以接收拖拽数据
                        return (true);

                    } else {
                        // 返回false. 在当前是拖拽和落下操作时，视图（View）将不再接收
                        // 事件直到发送ACTION_DRAG_ENDED
                        return (false);
                    }

                case DragEvent.ACTION_DRAG_ENTERED:

                    return (true);

                case DragEvent.ACTION_DRAG_LOCATION:
                    // 忽略该事件
                    return (true);

                case DragEvent.ACTION_DRAG_EXITED:

                    return (true);

                case DragEvent.ACTION_DROP:
                    // 获得item包括拖拽数据
                    ClipData.Item item = event.getClipData().getItemAt(0);
                    // 从item获得文本数据
                    CharSequence dragData = item.getText();

                    acceptInvitation(Integer.parseInt(dragData.toString()));


                    // 返回true. DragEvent.getResult()将会返回true.
                    return (true);

                case DragEvent.ACTION_DRAG_ENDED:


                    return (true);

                // 其他未知的action.
                default:

                    break;
            }

            return true;
        }
    }


    class AppointmentAdapter extends BaseDynamicGridAdapter {


        //1 invitations,2 participants,3 requests
        private int type;


        public AppointmentAdapter(Context context, List<?> items1, int columnCount, int type) {
            super(context, items1, columnCount);
            this.type = type;
        }

        @Override
        public View getView(final int position, View view, ViewGroup viewGroup) {

            final ListItem listItem = (ListItem) getItem(position);
            ImageView userPhotoView;
            TextView nicknameView;

            ViewCache viewCache;
            if (view == null) {
                view = LayoutInflater.from(getContext()).inflate(R.layout.user_image, null);
                userPhotoView = (ImageView) view.findViewById(R.id.user_photo);
                nicknameView = (TextView) view.findViewById(R.id.user_nickname);
                viewCache = new ViewCache(userPhotoView, nicknameView);
                view.setTag(viewCache);
            } else {
                viewCache = (ViewCache) view.getTag();
                userPhotoView = viewCache.userPhotoView;
                nicknameView = viewCache.nameView;
            }
            userPhotoView.getLayoutParams().width = listViewWidth;
            userPhotoView.getLayoutParams().height = listViewWidth;
            String userGuid = listItem.getGuid3();
            boolean me = token.getGuid().equals(userGuid);
            loadUserImage(userGuid, userPhotoView);
            nicknameView.getLayoutParams().width = listViewWidth;
            nicknameView.setText(me ? Constant.ME : listItem.getName());


            if (type == 1) {
                invitationsView.setChildTouchListener(view);

                if (me) {

                    dragLongClickListener = new DragLongClickListener(position);

                    //添加长按事件
                    view.setOnLongClickListener(dragLongClickListener);

                    // 创建一个拖拽的事件监听器
                    mDragListener = new DragEventListener();


                    // 拖拽反应区域
                    // 为该区域添加拖动事件监听器
                    participantsView.setOnDragListener(mDragListener);
                }
            } else if (type == 2) {
                participantsView.setChildTouchListener(view);
            } else {
                requestsView.setChildTouchListener(view);
            }

            return view;
        }
    }

    class ViewCache {

        private ImageView userPhotoView;

        private TextView nameView;


        public ViewCache(ImageView userPhotoView, TextView nameView) {
            this.userPhotoView = userPhotoView;
            this.nameView = nameView;
        }
    }

    private void appointmentRender(final UserToken token) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                json = ServerAccessHelper.queryStringForGet(RemoteUrlCollections.getUrl(UrlSuffix.APPOINTMENT) + "/" + appointmentGuid, token.getToken());
                getActivity().runOnUiThread(uiUpdate);
            }
        }).start();
    }

    private Runnable uiUpdate = new Runnable() {
        @Override
        public void run() {
            if (!Constant.RESPONSE_BADLY.equals(json)) {

                appointment = JsonUtils.toAppointment(json, token.getGuid());
                if (appointment != null) {
                    if (appointment.getInvitations().isEmpty()) {
                        invitationText.setVisibility(View.GONE);
                        invitationsView.setVisibility(View.GONE);
                    } else {
                        invitationText.setVisibility(View.VISIBLE);
                        invitationsView.setVisibility(View.VISIBLE);
                        invitationsAdapter.set(appointment.getInvitations());
                    }
                    participantsAdapter.set(appointment.getParticipants());
                    HuaWenHuPoTextView requestText = (HuaWenHuPoTextView) mainView.findViewById(R.id.request_text);
                    if (appointment.getRequests().isEmpty()) {
                        requestText.setVisibility(View.GONE);
                        requestsView.setVisibility(View.GONE);
                    } else {
                        requestText.setVisibility(View.VISIBLE);
                        requestsView.setVisibility(View.VISIBLE);
                        requestsAdapter.set(appointment.getRequests());
                    }
                    headerText.setText(appointment.getLocation());

                    HuaWenHuPoTextView timeView = (HuaWenHuPoTextView) mainView.findViewById(R.id.time);
                    timeView.setText(appointment.getPeriods());

                    HuaWenHuPoTextView noteView = (HuaWenHuPoTextView) mainView.findViewById(R.id.note);
                    noteView.setText(appointment.getPaymentWay() + "\n\n" + appointment.getNote());

                    if (appointment.isSendJoinRequest()) {
                        joinButton.setVisibility(View.VISIBLE);
                        joinButton.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                sendJoinRequest();
                            }
                        });
                    }
                }
            }
        }
    };


    private void sendJoinRequest() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                JSONObject paramJson = new JSONObject();
                try {
                    paramJson.put("appointmentGuid", appointmentGuid);
                    StringEntity paramEntity = new StringEntity(paramJson.toString(), Constant.CHARSET_UTF8);
                    final String result = ServerAccessHelper.queryStringForPost(RemoteUrlCollections.getUrl(UrlSuffix.APPOINTMENT_REQUEST), token.getToken(), paramEntity);
                    if (!Constant.RESPONSE_BADLY.equals(result)) {
                        final AppointmentRequest request = JsonUtils.toAppointmentRequest(result, appointmentGuid);
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (request != null) {

                                    Toast.makeText(getActivity(), getString(R.string.invite_send), Toast.LENGTH_SHORT).show();
                                    joinButton.setVisibility(View.GONE);
                                    ListItem listItem = new ListItem(null, request.getAppointmentGuid(), request.getSenderName());
                                    listItem.setGuid2(request.getRequestGuid());
                                    listItem.setGuid3(request.getSenderGuid());
                                    invitationText.setVisibility(View.VISIBLE);
                                    invitationsView.setVisibility(View.VISIBLE);
                                    invitationsAdapter.add(listItem);
                                }

                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void acceptInvitation(final int position) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                final ListItem listItem = (ListItem) invitationsAdapter.getItem(position);
                JSONObject paramJson = new JSONObject();
                try {
                    paramJson.put("guid", listItem.getGuid());
                    StringEntity paramEntity = new StringEntity(paramJson.toString(), Constant.CHARSET_UTF8);
                    String result = ServerAccessHelper.queryStringForPost(RemoteUrlCollections.getUrl(UrlSuffix.APPOINTMENT_INVITATION_ACCEPT), token.getToken(), paramEntity);
                    if (!Constant.RESPONSE_BADLY.equals(result)) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                participantsAdapter.add(listItem);
                                invitationsAdapter.remove(listItem);

                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }


    @Override
    public int getViewId() {
        return R.layout.join_appointment;
    }

    @Override
    public int getSourceId() {
        return R.id.join_appointment;
    }

    @Override
    public void updateUI() {

        appointmentRender(token);
    }
}
